#include <MutexLocker.h>

#define LOGGER_NAME "shadow.sutil.MutexLocker"

MutexLocker::MutexLocker(pthread_mutex_t * p_mutex) {
	_p_mutex = p_mutex;
	_is_locked = false;
	_logger = log4cxx::Logger::getLogger(LOGGER_NAME);
}

MutexLocker::~MutexLocker() {
	if (_is_locked) unlock();
}

int MutexLocker::lock() {
	if (!_is_locked) {
		int res = pthread_mutex_lock(_p_mutex);
		if (0 != res) return -1;
		_is_locked = true;
		return 1;
	}
	LOG4CXX_WARN(_logger, "trying to lock the already locked mutex");
	return 2;
}


int MutexLocker::unlock() {
	if (_is_locked) {
		int res = pthread_mutex_unlock(_p_mutex);
		if (0 != res) return -1;
		_is_locked = false;
		return 1;
	}
	LOG4CXX_WARN(_logger, "trying to unlock the already unlocked mutex");
	return 2;
}
